package com.telecom.hz.sample.controller;

import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileController {
	
	@Value("${application.upload.location.dest}")
	private String destDir;
	
	private static final Logger logger = LoggerFactory.getLogger(FileController.class);
	
	@RequestMapping(value="/file", method=RequestMethod.POST)
	public String file(//@RequestParam("name") String name,
//			@RequestParam("md5") String md5Str,
			@RequestParam("file") MultipartFile file) {
		if(!file.isEmpty()) {
			String contentType = file.getContentType();
			String fileName = file.getName();
			String originalFilename = file.getOriginalFilename();
			long size = file.getSize();
			
			logger.warn(String.format("\n originalFilename: %s\n fileName: %s\n"
					+ " contentType: %s\n size: %s", originalFilename, fileName, contentType, size));
			try {
				String path = destDir+File.separator+originalFilename;
				file.transferTo(new File(path));
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return String.format("\n originalFilename: %s\n fileName: %s\n"
					+ " contentType: %s\n size: %s", originalFilename, fileName, contentType, size);
		}else {
			logger.warn("empty file recieve");
			return "empty file recieve";
		}
	}
}
